<template>
	<div>
		<el-card shadow="never" style="height: 100%;" class="my">
			<template #header>
				<div class="flex-space-between">
					<div class="left">
						<div style="margin-right: 10px;" class="flex-align-center">
							<el-icon style="margin-right: 6px;" size="18px" color="#5283ff">
								<GoodsFilled />
							</el-icon>
							<!-- <el-text size="large">获客区间</el-text> -->
						</div>
						<el-date-picker v-model="dateText" placeholder="选择日期" @change="(e)=>onChange(e,'date')"
							type="data"></el-date-picker>
						<el-button @click="reset" type="primary" plain style="margin-left: 10px;">
							<el-icon size="16px">
								<Refresh />
							</el-icon>
							<span>刷新</span>
						</el-button>
					</div>
					<div class="right">
						<!--  -->
						<el-input v-model="searchText" @input="(e)=>onChange(e,'search')"
							style="width: 180px;margin-left: 20px;" placeholder="搜索">
							<template #suffix>
								<div class="my-a-min">
									<el-icon>
										<ArrowDown />
									</el-icon>
								</div>
								<el-divider direction="vertical" style="margin: 0;" />
								<div class="my-a-min">
									<el-icon color="#666">
										<Search />
									</el-icon>
								</div>
							</template>
						</el-input>
						<!--  -->
						<div style="margin: 0 10px;" class="flex-align">
							<el-tooltip placement="top" effect="light" content="导入">
								<div class="my-a-min">
									<el-icon>
										<Download />
									</el-icon>
								</div>
							</el-tooltip>
							<!--  -->
							<!--  -->
							<el-tooltip placement="top" effect="light" content="导出">
								<div @click="exportExcel" class="my-a-min">
									<el-icon>
										<Upload />
									</el-icon>
								</div>
							</el-tooltip>
							<!--  -->
							<el-tooltip placement="top" effect="light" content="更多">
								<div class="my-a-min">
									<el-icon color="#676967">
										<MoreFilled />
									</el-icon>
								</div>
							</el-tooltip>
							<!--  -->
						</div>

						<el-button @click="openUpdatePage()" type="primary" class="flex-space-between">
							<el-text style="color: #fff;margin-right: 6px;">创建</el-text>
							<el-icon>
								<ArrowDown />
							</el-icon>
						</el-button>
					</div>
				</div>
			</template>
			<!--  -->
			<el-table @cell-mouse-enter="mouseEnter" v-loading="loading" :data="tableData" :stripe="false"
				table-layout="auto" :default-sort="{}" border
				style="width: 100%;height: calc(100vh - 205px);margin-top: -1px;" class="my">
				<el-table-column :type="tableTypeIs?'selection':''" width="76" fixed="left" prop="productId"
					:sortable="false">
					<template #header>
						<!-- selection -->
						<el-checkbox v-model="tableTypeIs" size="large" />
					</template>
				</el-table-column>
				<el-table-column width="140" prop="productCode" label="商品编码" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="productName" label="商品名称" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="model" label="规格型号" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="productClassificationId" label="商品分类" :sortable="false">
					<template #default="scope">
						<el-tag size="small" style="border: 0;" v-if="scope.row?.productClassification?.label"
							:color="scope.row?.productClassification.color" round effect="dark">
							{{ scope.row?.productClassification.label }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column width="140" prop="unitId" label="单位" :sortable="false">
					<template #default="scope">
						<el-tag size="small" style="border: 0;" v-if="scope.row?.unit?.label"
							:color="scope.row?.unit.color" round effect="dark">
							{{ scope.row?.unit.label }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column width="140" prop="imageUrl" label="产品图片" :sortable="false">
					<template #default="scope">
						<el-image style="width: 30px; height: 30px" :src="scope.row.imageUrl"
							:preview-src-list="[scope.row.imageUrl]" preview-teleported />
					</template>
				</el-table-column>
				<el-table-column width="140" prop="currentInventory" label="当前库存数量" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="onWayAmount" label="采购在途数量" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="initialInventory" label="期初库存数量" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="stockLowerLimit" label="库存下限" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="warehouseId" label="仓库" :sortable="false">
					<template #default="scope">
						<el-tag size="small" style="border: 0;" v-if="scope.row?.warehouse?.warehouseName"
							color="#86a3bf" round effect="dark">
							{{ scope.row?.warehouse.warehouseName }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column width="140" prop="costPrice" label="成本单价"
					:formatter="(row, column, cellValue, index)=>formatNumber(cellValue,'元')" :sortable="false">
				</el-table-column>
				<el-table-column width="140" prop="sellingPrice" label="销售单价"
					:formatter="(row, column, cellValue, index)=>formatNumber(cellValue,'元')" :sortable="false">
				</el-table-column>
				<el-table-column prop="applicant" fixed="right" width="166" label="操作" :sortable="false">
					<template #default="scope">
						<div class="flex-align">
							<el-button @click="dialogVisible=true" type="danger" size="small" auto-insert-space>
								<el-icon size="16px">
									<Delete />
								</el-icon>
								<span>删除</span>
							</el-button>
							<el-button @click="openEdit(scope.row.productId)" type="success" plain size="small"
								auto-insert-space>
								<el-icon size="16px">
									<Edit />
								</el-icon>
								<span>编辑</span>
							</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!--  -->
			<el-pagination class="my" style="height: 40px;padding-left: 10px;" @change="(e)=>onChange(e,'pagination')"
				layout="total, prev, pager, next, jumper" :page-count="pageData.pages" :total="pageData.total">
			</el-pagination>
		</el-card>
		<!-- 弹框 -->
		<el-dialog v-model="dialogVisible" width="300" align-center append-to-body>
			<el-text size="large">{{dialogTitle}}</el-text>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false" text bg>取消</el-button>
					<el-button @click="dialogVisible = false" type="danger">
						删除
					</el-button>
				</div>
			</template>
		</el-dialog>
		<!--  -->
		<Update ref="updateRef" @update="updateData"></Update>
	</div>
</template>

<script setup lang="ts">
	import { ref, reactive, computed, onMounted } from 'vue';
	import { useRouter } from 'vue-router';
	import {DocumentChecked, GoodsFilled, Refresh, MoreFilled, ArrowDown, Download, Upload, Search, List, Delete, Edit } from '@element-plus/icons-vue';
	import request from '../../utils/request';
	import { removeEmptyProperties, formatNumber, mergeObjects } from '../../utils/index';
	import { formatDate } from '../../utils/date';
	import Update from './inventoryTable-child/update.vue';
	import { ElMessage } from 'element-plus';
	import ExcelJS from "exceljs";
	import FileSaver from "file-saver";
	import { formatTableData } from '../../utils/mixins';
	//
	const router = useRouter();
	const updateRef = ref(null);
	const loading = ref(false);
	const dateText = ref(null);
	const searchText = ref(null);
	const tableTypeIs = ref(false);
	const pageData = ref({
		pageNum: 1,
		pageSize: 8,
		total: 0,
		pages: 0,
		customerName: '',
		status: '',
		orderNumber: '',
		outboundNumber: ''
	});

	const dialogVisible = ref(false);
	const dialogTitle = computed(() => {
		let msg = '确定删除一条数据？';
		return msg;
	});
	//表格数据
	const tableData = ref([]);
	onMounted(() => {
		getPageList();
	});
	//改变/
	const onChange = (e : any, type : string) => {
		// 搜索框
		if (type === 'search') {
			console.log('search--->', e);
			if (!isNaN(e)) {
				pageData.value.status = e;
			}
			pageData.value.customerName = e;
			pageData.value.orderNumber = e;
			pageData.value.outboundNumber = e;
		}
		// 分页
		if (type === 'pagination') {
			pageData.value.pageNum = e;
		}
		//
		getPageList();
	};
	//鼠标悬浮单元格
	const mouseEnter = (row : any, column : any, cell : HTMLTableCellElement, event : Event) => {
		// console.log('row-customerId--->', row.customerId);
	}
	//获取分页数据
	const getPageList = async () => {
		loading.value = true;
		const result = await request({
			url: '/demand/selectProductAll',
			params: pageData.value,
		});
		//
		console.log('getPageList --->', result);
		//
		pageData.value = mergeObjects(pageData.value, result.data.t);
		//
		tableData.value = result.data.t.list;
		//
		loading.value = false;
		//
		getproductClassificationList();
		getunitList();
		//
		return loading.value;
	};
	//获取商品分类
	const getproductClassificationList = async () => {
		formatTableData(tableData.value, 'productClassificationId', 'productClassification', 'product_classification', 'option');
	}
	//获取单位
	const getunitList = async () => {
		formatTableData(tableData.value, 'unitId', 'unit', 'unit', 'option');
	}
	//重置
	const reset = async () => {
		pageData.value = {
			pageNum: 1,
			pageSize: 8,
			total: 0,
			pages: 0,
			customerName: '',
			status: '',
			orderNumber: '',
			outboundNumber: ''
		};
		dateText.value = null;
		searchText.value = null;
		//
		const is = await getPageList();
		if (!is) {
			ElMessage.success({
				showClose: true,
				message: '刷新成功！'
			});
		}
	}
	//打开编辑面板
	const openUpdatePage = () => {
		updateRef.value.openDialog();
	}
	//打开编辑面板 并带参
	const openEdit = (id : string | number) => {
		router.push({ query: { id } });
		openUpdatePage();
	}
	//监听更新
	const updateData = () => {
		getPageList();
	}
	//
	// 导出excel文件
	const exportExcel = () => {
		// 创建工作簿
		const workbook = new ExcelJS.Workbook();
		// 添加工作表，名为sheet1
		const sheet1 = workbook.addWorksheet("sheet1");
		// 导出数据列表
		const data = tableData.value;
		// 获取表头所有键
		const headers = Object.keys(data[0]);
		// 将标题写入第一行
		sheet1.addRow(headers);
		// 将数据写入工作表
		data.forEach((row) => {
			const values = Object.values(row);
			sheet1.addRow(values);
		});
		// 导出表格文件
		workbook.xlsx.writeBuffer().then((buffer) => {
			const file = new Blob([buffer], { type: "application/octet-stream" });
			FileSaver.saveAs(file, `${formatDate(new Date())}.xlsx`);
		}).catch(error => console.log('Error writing excel export', error));
	}
</script>
<style>
	@import '../../assets/css/index.css';
</style>
<style scoped lang="scss">
	@import '../../assets/css/index.scss';
</style>